//
//  JPModifyAddrController.m
//  精品酒店
//
//  Created by DIANGHONG on 2018/5/18.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "JPModifyAddrController.h"

@interface JPModifyAddrController ()<CLLocationManagerDelegate>

@property (nonatomic,strong ) CLLocationManager *locationManager;//定位服务
@property (nonatomic,copy) NSString *currentCity;   //城市
@property (nonatomic,copy) NSString *strLatitude;   //经度
@property (nonatomic,copy) NSString *strLongitude;  //维度
@property (weak, nonatomic) IBOutlet UIButton *saveAddrButton;
@property (weak, nonatomic) IBOutlet UITextField *nameTxtField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTxtField;
@property (weak, nonatomic) IBOutlet UIButton *locButton;
@property (weak, nonatomic) IBOutlet UITextField *addressTxtField;

@end

@implementation JPModifyAddrController
+ (instancetype)modifyVCWithModel:(DHAddressModel *)model
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"JPPostTaskController" bundle:nil];
    JPModifyAddrController *vc = [sb instantiateViewControllerWithIdentifier:@"modifyVCID"];
    vc.model = model;
    return vc;
}
- (void)locatemap{
    
    if ([CLLocationManager locationServicesEnabled]) {
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.delegate = self;
        [_locationManager requestAlwaysAuthorization];
        _currentCity = [[NSString alloc]init];
        [_locationManager requestWhenInUseAuthorization];
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 5.0;
        [_locationManager startUpdatingLocation];
    }
}
#pragma mark: - 定位按钮点击事件
- (IBAction)locButtonClick:(UIButton *)sender
{
    [self locatemap];
}

- (void)viewDidLoad {
    [super viewDidLoad];
 
    self.saveAddrButton.layer.masksToBounds = true;
    self.saveAddrButton.layer.cornerRadius = 6;
    if (self.model) {
        self.nameTxtField.text = self.model.true_name;
        self.phoneTxtField.text = self.model.mob_phone;
        [self.locButton setTitle:self.model.area_info forState:UIControlStateNormal];
        self.addressTxtField.text = self.model.address;
    }
 
}
#pragma mark: - 保存地址按钮监听
- (IBAction)saveAdrButtonClick:(UIButton *)sender
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if (!self.nameTxtField.hasText) {
        [SVProgressHUD showInfoWithStatus:@"请输入姓名"];
        return;
    }
    if (!self.phoneTxtField.hasText) {
        [SVProgressHUD showInfoWithStatus:@"请输入手机号"];
        return;
    }
    if (!self.addressTxtField.hasText) {
        [SVProgressHUD showInfoWithStatus:@"请输入详细地址"];
        return;
    }
    if ([self.locButton.currentTitle isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请点击定位"];
        return;
    }
    param[@"true_name"] = self.nameTxtField.text;
    param[@"address"] = self.addressTxtField.text;
    param[@"mob_phone"] = self.phoneTxtField.text;
    param[@"lng"] = self.strLongitude;
    param[@"lat"] = self.strLatitude;
    
    //编辑地址
    if (self.model)
    {
        param[@"id"] = self.model.address_id;
        [DHNetworkManager.shareManager postEditAddressWithUrl:kEditAddressUrl param:param completion:^(BOOL isSuccess, NSString *statusInfo)
        {
            if (!isSuccess)
            {
                [SVProgressHUD showErrorWithStatus:statusInfo];
                return ;
            }
            [SVProgressHUD showSuccessWithStatus:statusInfo];
            [self.navigationController popViewControllerAnimated:true];
            NSAssert(self.editOrAddAddressBlock != nil, @"self.editOrAddAddressBlock 不能为nil");
            self.editOrAddAddressBlock();
        }];
    }else{
        //添加地址
        [DHNetworkManager.shareManager postEditAddressWithUrl:kAddAdressUrl param:param completion:^(BOOL isSuccess, NSString *statusInfo)
        {
            if (!isSuccess)
            {
                [SVProgressHUD showErrorWithStatus:statusInfo];
                return ;
            }
            [SVProgressHUD showSuccessWithStatus:statusInfo];
            [self.navigationController popViewControllerAnimated:true];
            NSAssert(self.editOrAddAddressBlock != nil, @"self.editOrAddAddressBlock 不能为nil");
            self.editOrAddAddressBlock();
        }];
    }
}
#pragma mark - 定位成功
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    
    [_locationManager stopUpdatingLocation];
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //当前的经纬度
    NSLog(@"当前的经纬度 %f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
    
    self.strLongitude = [NSString stringWithFormat:@"%f",currentLocation.coordinate.longitude];
    self.strLatitude =  [NSString stringWithFormat:@"%f",currentLocation.coordinate.latitude];;
    //这里的代码是为了判断didUpdateLocations调用了几次 有可能会出现多次调用 为了避免不必要的麻烦 在这里加个if判断 如果大于1.0就return

        //地理反编码 可以根据坐标(经纬度)确定位置信息(街道 门牌等)
        [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (placemarks.count >0) {
                CLPlacemark *placeMark = placemarks[0];
                self->_currentCity = placeMark.locality;
                NSString *province = placeMark.administrativeArea;
                if (!self->_currentCity) {
                    self->_currentCity = @"无法定位当前城市";
                }
                //看需求定义一个全局变量来接收赋值
                //            NSLog(@"当前国家 - %@",placeMark.country);//当前国家
                NSLog(@"当前城市 - %@,%@",self->_currentCity,province);//当前城市
                NSString *addressInfo = [NSString stringWithFormat:@"%@%@%@",placeMark.administrativeArea,placeMark.locality,placeMark.subLocality];
                [self.locButton setTitle:addressInfo forState:UIControlStateNormal];
                //[self.addrBtn setTitle:self->_currentCity forState:UIControlStateNormal];
                //            NSLog(@"当前位置 - %@",placeMark.subLocality);//当前位置
                //            NSLog(@"当前街道 - %@",placeMark.thoroughfare);//当前街道
                //            NSLog(@"具体地址 - %@",placeMark.name);//具体地址
                NSString *message = [NSString stringWithFormat:@"%@,%@,%@,%@,%@",placeMark.country,self->_currentCity,placeMark.subLocality,placeMark.thoroughfare,placeMark.name];
                
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"好", nil];
                //            [alert show];
            }else if (error == nil && placemarks.count){
                
                NSLog(@"NO location and error return");
            }else if (error){
                
                NSLog(@"loction error:%@",error);
            }
        }];
    //[self loadHomeTaskListWithPullUP:NO];
}
#pragma mark - 定位失败
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication]openURL:settingURL];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cancel];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}

@end
